//
//  TLAddItemWindow.m
//  FMDB_Test_Demo
//
//  Created by tao故乡的云 on 2017/4/9.
//  Copyright © 2017年 故乡的云 . All rights reserved.
//

#import "TLAddItemWindow.h"
#import <Masonry/Masonry.h>

#pragma mark - TLItemView
@interface TLItemView ()
/** 标题 */
@property (nonatomic, weak) UILabel *titleLabel;

@end

@implementation TLItemView
/// @ text 可为 nil
+ (instancetype)itemViewWithTitle:(NSString *)title {
    
    TLItemView *itemView = [[self alloc] init];
    [itemView addSubviews];
    [itemView setConstraints];
    itemView.title = title;
    itemView.titleLabel.text = title;
    itemView.layer.cornerRadius = 5;
    return itemView;
}

/// 添加子元素
- (void)addSubviews {
    UILabel *label = [[UILabel alloc] init];
    self.titleLabel = label;
    [label sizeToFit];
    [self addSubview:label];
//    label.backgroundColor = [UIColor blueColor];

    UITextField *textField = [[UITextField alloc] init];
    self.textField = textField;
    textField.clipsToBounds = NO;
    textField.returnKeyType = UIReturnKeyNext;
    textField.borderStyle = UITextBorderStyleLine;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self addSubview:textField];
//    textField.backgroundColor = [UIColor redColor];
}

/// 约束设置
- (void)setConstraints {
    __weak TLItemView *weakSelf = self;
    CGFloat marginV = 2;
    CGFloat marginH = 5;
    CGFloat titleLableW = 50;
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf).offset(marginH);
        make.top.equalTo(weakSelf).offset(marginV);
        make.bottom.equalTo(weakSelf).offset(-marginV);
        make.width.equalTo(@(titleLableW));
    }];
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.titleLabel.mas_right).offset(marginH);
        make.right.equalTo(weakSelf).offset(-marginH);
        make.top.equalTo(weakSelf).offset(marginV);
        make.bottom.equalTo(weakSelf).offset(-marginV);
    }];
}

@end


#pragma mark - TLAddItemWindow

typedef void(^doneButtonClick)(TLChengYu *);

@interface TLAddItemWindow ()<UITextFieldDelegate>
@property(nonatomic, weak) UIView *contentView;
@property(nonatomic, weak) UIButton *doneBtn;
@property(nonatomic, weak) UIButton *cancelBtn;
@property(nonatomic, strong) doneButtonClick done;
@property(nonatomic, strong) NSMutableArray <TLItemView *> *itemViews;
@end


@implementation TLAddItemWindow
static TLAddItemWindow *_obj;

/// @ item ：要编辑的词条,可为nil
+ (instancetype)showWithItem:(TLChengYu *)item doneButtonClick:(void (^)(TLChengYu * _Nonnull))done {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        TLAddItemWindow *addWindow = [[self alloc] initWithFrame:[UIScreen mainScreen].bounds];
        addWindow.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.1];
        [addWindow addSubviews];
        [addWindow setConstraints];
        // 手势注销编辑状态
        [addWindow addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:addWindow action:@selector(endEditing)]];
        addWindow.windowLevel = UIWindowLevelAlert;
        [addWindow makeKeyAndVisible];
        _obj = addWindow;
    });
    _obj.item = item;
    if (done) {
        _obj.done = done;
    }
    _obj.hidden = NO;
    return _obj;
}

- (void)addSubviews {
    // contentView
    UIView *contentView = [[UIView alloc] init];
    self.contentView = contentView;
    contentView.layer.cornerRadius = 10; // 圆角
    [self addSubview:contentView];
    contentView.backgroundColor = [UIColor colorWithRed:0.7 green:0.8 blue:0.9 alpha:0.9];
    
    // 细分栏目
    [self addItemViewWithTitle:@"词条:" placeholder:@"请出入词条（*必填）"];
    [self addItemViewWithTitle:@"拼音:" placeholder:@"请出入词条拼音（*必填）"];
    [self addItemViewWithTitle:@"注释:" placeholder:@"请出入词条注释"];
    [self addItemViewWithTitle:@"例句:" placeholder:@"请出入词条例句"];
    TLItemView *dianGuView = [self addItemViewWithTitle:@"出处:" placeholder:@"请出入词条出处"];
    dianGuView.textField.returnKeyType = UIReturnKeyDone;
    // 按钮
    self.cancelBtn = [self addButtonWithTitle:@"取  消"];
    self.doneBtn = [self addButtonWithTitle:@"确  定"];
    self.doneBtn.enabled = NO;
}

- (UIButton *)addButtonWithTitle:(NSString *)title {
    UIButton *btn = [[UIButton alloc] init];
    [self.contentView addSubview:btn];
    btn.backgroundColor = [UIColor colorWithRed:0.9 green:0.8 blue:0.6 alpha:1.0];
    btn.layer.cornerRadius = 6;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    return btn;
}

- (TLItemView *)addItemViewWithTitle:(NSString *)title placeholder:(NSString *)placeholder {
    TLItemView *itemView = [TLItemView itemViewWithTitle:title];
    itemView.textField.placeholder = placeholder;
    itemView.textField.delegate = self;
    [self.contentView addSubview:itemView];
    [self.itemViews addObject:itemView];
    itemView.backgroundColor = [UIColor colorWithRed:1 green:0.9 blue:0.9 alpha:0.9];
    return itemView;
}

- (void)endEditing {
    [self.contentView endEditing:YES];
}

- (void)btnClick:(UIButton *)btn {
    [self.contentView endEditing:YES];
    if ([btn isEqual:self.doneBtn]) { // 确定
        // 获取item
        TLChengYu *item = [[TLChengYu alloc] init];
        item.name = self.itemViews[0].textField.text;
        item.pinYin = self.itemViews[1].textField.text;
        item.zhuShi = self.itemViews[2].textField.text;
        item.liJu = self.itemViews[3].textField.text;
        item.dianGu = self.itemViews[4].textField.text;
        
        self.done(item);
    }
    self.hidden = YES;
}

#pragma mark layout sub views
/// 约束设置
- (void)setConstraints {
    
    __weak TLAddItemWindow *weakSelf = self;
    CGFloat marginV = 14;
    CGFloat marginH = 14;
    CGFloat contentViewW = 300;
    CGFloat contentViewH = 300;
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(contentViewW));
        make.height.equalTo(@(contentViewH));
        make.centerX.equalTo(weakSelf);
        make.top.equalTo(weakSelf).offset(100);
    }];
    
    UIView *previousView = nil;
    for (TLItemView *view in self.itemViews) {
        if (previousView == nil) {
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(weakSelf.contentView.mas_top).mas_offset(@(marginV));
                make.left.equalTo(weakSelf.contentView.mas_left).mas_offset(@(marginH));
                make.right.equalTo(weakSelf.contentView.mas_right).mas_offset(@(-marginH));
                make.height.equalTo(@30);
            }];
        }else {
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(previousView.mas_bottom).mas_offset(@(marginV));
                make.left.equalTo(weakSelf.contentView.mas_left).mas_offset(@(marginH));
                make.right.equalTo(weakSelf.contentView.mas_right).mas_offset(@(-marginH));
                make.height.equalTo(@30);
            }];
        }
        previousView = view;
    }
    
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.contentView.mas_left).mas_offset(@(1.5 * marginH));
        make.bottom.equalTo(weakSelf.contentView).mas_offset(@(- 1.5 * marginV));
        CGFloat W = (contentViewW - 3 * 1.5 * marginH) * 0.5;
        make.width.equalTo(@(W));
        make.height.equalTo(@30);
    }];
    
    [self.doneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.contentView.mas_right).mas_offset(@(-1.5 * marginH));
        make.bottom.equalTo(weakSelf.contentView).mas_offset(@(- 1.5 * marginV));
        make.size.equalTo(weakSelf.cancelBtn);
    }];

}

#pragma mark textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    TLItemView *itemView = (TLItemView *)textField.superview;
    NSInteger index = [self.itemViews indexOfObject:itemView];
    if (index == self.itemViews.count - 1) { // 最后一项
        if (self.doneBtn.enabled) {
            [self btnClick:self.doneBtn];
        }
        [self.contentView endEditing:YES];
    }else { // 下一项
        UITextField *textF = self.itemViews[index + 1].textField;
        [textF becomeFirstResponder];
    }
    return YES;
}

// 监听输入
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    self.doneBtn.enabled = (self.itemViews[0].textField.text.length > 0) &&
    (self.itemViews[0].textField.text.length > 0);
    return YES;
}

#pragma mark properties

- (NSMutableArray<TLItemView *> *)itemViews {
    if (!_itemViews) {
        _itemViews = [NSMutableArray array];
    }
    return _itemViews;
}

- (void)setItem:(TLChengYu *)item {
    _item = item;
    self.itemViews[0].textField.text = item.name;
    self.itemViews[1].textField.text = item.pinYin;
    self.itemViews[2].textField.text = item.zhuShi;
    self.itemViews[3].textField.text = item.liJu;
    self.itemViews[4].textField.text = item.dianGu;
    self.doneBtn.enabled = (self.itemViews[0].textField.text.length > 0) &&
    (self.itemViews[0].textField.text.length > 0);
}

@end

